package com.gitee.ywj1352.kafka.origin;


import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.IntegerSerializer;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;
public class KafkaProducerDemo {


    public static KafkaProducer<String, String> kafkaProducer;

    public static final String TOPIC_NAME = "ywj_test_kafka";

    //初始化 生产者
    public static void init(){
        Properties props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092,127.0.0.1:9093,127.0.0.1:9094");
        //重试，0为不启用重试机制
        props.put(ProducerConfig.RETRIES_CONFIG, 1);
        //控制批处理大小，单位为字节
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384);
        //批量发送，延迟为1毫秒，启用该功能能有效减少生产者发送消息次数，从而提高并发量
        props.put(ProducerConfig.LINGER_MS_CONFIG, 1);
        //生产者可以使用的总内存字节来缓冲等待发送到服务器的记录
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 1024000);
        //键的序列化方式
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class);
        //值的序列化方式
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        //需要添加事务Id
        props.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "transactionId");

        kafkaProducer = new KafkaProducer<>(props);
    }


    // 开启事务 通过 发送消息
    public static void sendByTransaction() {
        kafkaProducer.initTransactions();
        kafkaProducer.beginTransaction();
        ProducerRecord<String, String> pr1 = new ProducerRecord<>(TOPIC_NAME, "ywj-hi-hello-1");
        ProducerRecord<String, String> pr2 = new ProducerRecord<>(TOPIC_NAME, "ywj-hi-hello-2");
        ProducerRecord<String, String> pr3 = new ProducerRecord<>(TOPIC_NAME, "ywj-hi-hello-3");
        kafkaProducer.send(pr1);
        kafkaProducer.send(pr2);
        kafkaProducer.send(pr3);
        //提交事务
        kafkaProducer.commitTransaction();
        //撤销事务
        //kafkaProducer.abortTransaction();
    }

    public static void main(String[] args) throws Exception {
        init();
        sendByTransaction();
    }


}
